"""
    create by IAmFiveHigh on 2024/5/23
"""
from typing import List

from LA.Vector import Vector
from LA.Matrix import Matrix
from LA.LinearSystem import rank


def gram_schmidt_process(basis: List['Vector']) -> List['Vector']:
    _guard_linearly_independent(basis)

    # 保存第一个向量
    res = [basis[0]]

    for i in range(1, len(basis)):
        p = basis[i]
        for r in res:
            # 一维投影求正交基方法
            p = p - basis[i].dot(r) / r.dot(r) * r
        res.append(p)
    return res


def _guard_linearly_independent(bases):
    # 确保传入向量组线性无关
    m = Matrix(bases)
    if rank(m) != len(m):
        raise Exception(f"Error: 向量组{m}线性相关")
